<template>
  <el-form
    ref="ruleFormRef"
    :model="ruleForm"
    status-icon
    :rules="rules"
    label-width="120px"
    class="demo-ruleForm"
  >
    <el-form-item label="姓名" prop="name">
      <el-col :span="4">
        <el-input v-model="ruleForm.name" type="text" autocomplete="off" />
      </el-col>
    </el-form-item>
    <el-form-item label="性别" prop="gender">
      <el-col :span="4">
        <el-select v-model="ruleForm.gender" placeholder="请选择性别">
          <el-option label="男" value="1" />
          <el-option label="女" value="0" />
        </el-select>
      </el-col>
    </el-form-item>
    <el-form-item label="年龄" prop="age">
      <el-col :span="4"
        ><el-input type="number" v-model.number="ruleForm.age" />
      </el-col>
    </el-form-item>
    <el-form-item label="出生年月" prop="birth">
      <el-col :span="6">
        <el-date-picker
          v-model="ruleForm.birth"
          placeholder="请选择出生日期"
          type="date"
          style="width: 100%"
          @change="setDate"
        />
      </el-col>
    </el-form-item>
    <el-form-item label="省市区" prop="selectedAddr">
      <el-col :span="6"
        ><UserCascader
          @sendUserAddress="sendUserAddress"
          v-model="ruleForm.selectedAddr"
        ></UserCascader>
      </el-col>
    </el-form-item>
    <el-form-item label="详细地址" prop="detailAddress">
      <el-col :span="11"
        ><el-input
          placeholder="请输入详细地址（例如xxx街道xxx号）"
          v-model="ruleForm.detailAddress"
      /></el-col>
      <el-col :offset="1" :span="4"
        ><el-button type="primary" @click="handleEdit"
          >跳转到当前地址</el-button
        ></el-col>
    </el-form-item>

    <el-form-item>
      <el-button type="primary" @click="submitForm">提交</el-button>
      <el-button @click="resetForm(ruleFormRef)">重置</el-button>
      <el-button @click="cancelAdd">取消</el-button>
    </el-form-item>
  </el-form>

<!-- 
  class: 必须指定宽高样式
  center: 中心点位置, 包含经纬度的对象 {lng, lat}
  zoom: 缩放的比例值

  @ready: 地图组件渲染完毕时触发, 返回一个百度地图的核心类和地图实例
  scroll-wheel-zoom: 是否滚轮缩放
-->
<baidu-map
  class="map"
  :center="center"
  :zoom="zoom"
  @ready="ready"
  :scroll-wheel-zoom="true"
>
  <!-- 比例尺-->
  <bm-scale anchor="BMAP_ANCHOR_TOP_RIGHT" />
  <!--缩放控件-->
  <bm-navigation
    anchor="BMAP_ANCHOR_TOP_RIGHT"
    :offset="{ height: 50, width: 50 }"/>
  <!-- 地图类型控件 -->
  <bm-map-type
    anchor="BMAP_ANCHOR_TOP_RIGHT"
    :map-types="['BMAP_NORMAL_MAP', 'BMAP_HYBRID_MAP']"/>
  <!--覆盖物 点 -->
  <bm-marker
    animation="BMAP_ANIMATION_BOUNCE"
    :position="detail"
    :dragging="true"/>
</baidu-map>
</template>

<script lang="ts" setup>
import type { FormInstance, FormRules } from "element-plus";
import { reactive, ref, watch } from "vue";
import { useGeocoder, usePoint } from "vue-baidu-map-3x";
import { ElMessage } from "element-plus";
import { ShowStatus } from "../types";
import { addUserInfoListApi } from "@/api/mock/userInfo";
// 用户选择的地址
const userAddress = ref<string>("");
// 用户填写的详细文字地址
// const detailAddress = ref<string>("");
const ruleFormRef = ref<FormInstance>();
const ruleForm = reactive({
  name: "",
  gender: "",
  age: 0,
  birth: "",
  selectedAddr: [],
  detailAddress: "",
});

//设置出生日期
const setDate = (e: any) => {
  const today = new Date();
  ruleForm.age = today.getFullYear() - e.getFullYear();
};

//校验规则
const rules = reactive<FormRules>({
  name: [{ required: true, message: "请填写姓名", trigger: "blur" }],
  gender: [{ required: true, message: "请勾选性别", trigger: "change" }],
  birth: [
    {
      type: "date",
      required: true,
      message: "请填写出生年月",
      trigger: "change",
    },
  ],
  userAddress: [
    {
      type: 'array',
      len: 3,
      message: '请输入省市区'
    },
  ],
  detailAddress: [
    { required: true, message: "请填写详细地址", trigger: "blur" },
  ],
});

/**地图代码**/
// 中心点位置
const center = ref({ lng: 121.254, lat: 31.0731 });
// 当前定位位置点
const location = ref({ lng: 121.254, lat: 31.0731 });
// 当前定位位置地址
const locationAddress = ref<string>("");
// 缩放比例
const zoom = ref(16);
// 用户填写的详细地址坐标
const detail = ref({ lng: 121.254, lat: 31.0731 });
// 用户的省市区信息保存
const province = ref<string>("");
const city = ref<string>("");
const area = ref<string>("");
const ready = ({ BMap, map }: any) => {
  // useGeocoder: 得到地址解析器对象geocode
  // usePoint: 得到指定经纬度值的point对象
  useGeocoder().then((geocode: any) => {
    usePoint(location.value.lng, location.value.lat).then((point: any) => {
      // 得到指定point点的地址位置
      geocode.getLocation(point, (result: any) => {
        console.log('--', result)
        locationAddress.value = result.address;
      });
    });
  });
 
  // 获取当前的地理位置并保存在center坐标中
  let geolocation = new BMap.Geolocation();
  geolocation.getCurrentPosition(function (r: any) {
    if (this.getStatus() == BMAP_STATUS_SUCCESS) {
      console.log(r)
      
      // 创建当前位置的覆盖物
      let mk = new BMap.Marker(r.point);
      // 添加覆盖物
      map.addOverlay(mk);
      // 保存中心点和location为当前坐标位置
      center.value = { lng: r.point.lng, lat: r.point.lat };
      location.value = { lng: r.point.lng, lat: r.point.lat };
    } else {
      console.warn("获取当前地理位置失败");
    }
  });
};

// 填写详细地址后修改地图中心位置
const handleEdit = () => {
  if (userAddress.value.trim() === "") {
    ElMessage.error("请选择省市区!");
    return;
  }
  if (ruleForm.detailAddress.trim() === "") {
    ElMessage.error("请输入街道的详细地址!");
    return;
  }
  useGeocoder().then((geocoder: any) => {
    geocoder.getPoint(userAddress.value + ruleForm.detailAddress, (res: any) => {
      center.value.lng = res.lng;
      center.value.lat = res.lat;
      detail.value = { lng: res.lng, lat: res.lat };
    });
  });
};

// 接收用户选择的地址信息
const sendUserAddress = (val: any[]): void => {
  console.log('sendUserAddress', val)
  province.value = val[0];
  city.value = val[1];
  area.value = val[2];
  userAddress.value = val.join("");
};

// 监控坐标点位置，并返回坐标点位置的坐标地理位置（文字）
watch(
  location,
  (value) => {
    useGeocoder().then((geocoder: any) => {
      // usePoint 通过坐标值返回百度坐标点对象
      usePoint(value.lng, value.lat).then((point: any) => {
        console.log('去获取地址')
        // 得到坐标点对应的地址, 显示到页面上
        geocoder.getLocation(point, (result: any) => {
          console.log(result)
          const {province, city, district, street, streetNumber} = result.addressComponents
          sendUserAddress([province, city, district])
          ruleForm.detailAddress = street + streetNumber;
          userAddress.value = result.address
          alert('得到地址: ' + result.address)
        });
      });
    });
  },
  { deep: true }
);
/** 表单提交 **/
const emits = defineEmits(["setShowStatus"]);
const id = ref<number>(Math.random());
const sort = ref<number>(Math.random() * 100);
const submitForm = async () => {
  await ruleFormRef.value?.validate();
  const date = new Date(ruleForm.birth);
  const formattedDate = date.toISOString().split("T")[0];
  ruleForm.birth = formattedDate;
  const res = await addUserInfoListApi({
    ...ruleForm,
    province: province.value,
    city: city.value,
    area: area.value,
    address: `${userAddress.value}${ruleForm.detailAddress}`,
    sort: sort.value++,
    id: id.value++,
  });
  if (res.status === 201) {
    emits("setShowStatus", ShowStatus.USER_LIST);
  }
};
//重置按钮
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};
//取消添加
const cancelAdd = () => {
  emits("setShowStatus", ShowStatus.USER_LIST);
};
</script>
<style lang="scss">
.map {
  width: 80%;
  height: 400px;
  margin: 0 auto;
}
</style>
